package com.jiazhong.boot.security.config;

import com.jiazhong.boot.security.exception.LoginFailException;
import com.jiazhong.boot.security.exception.LoginSuccessHandler;
import com.jiazhong.boot.security.exception.NotAccessException;
import com.jiazhong.boot.security.exception.NotLoginException;
import com.jiazhong.boot.security.filter.IsLoginSecurityFilter;
import com.jiazhong.boot.security.filter.TokenSecurityFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ObservationAuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@Configuration
public class SpringSecurityConfig{

    @Resource
    private NotAccessException notAccessException;
    @Resource
    private NotLoginException notLoginException;
    @Resource
    private LoginFailException loginFailException;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private IsLoginSecurityFilter isLoginSecurityFilter;
    @Resource
    private AuthenticationConfiguration config;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

/*
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails =
                User.withUsername("admin")
                        .password(passwordEncoder().encode("123456"))
                        .roles("admin")
                        .build();
        return new InMemoryUserDetailsManager(userDetails);
    }
*/

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin((formLogin) -> formLogin
                        //指定自定义登录页面地址
                        .loginPage("/login.html")
                        //登录访问路径：前台界面提交表单之后跳转到这个路径进行UserDetailsService的验证，必须和表单提交接口一样
                        .loginProcessingUrl("/user/login")
                        //认证成功之后跳转的路径
                        .defaultSuccessUrl("/index.html")
                // .successHandler(loginSuccessHandler)
                // .failureHandler(loginFailException)
        );

        //对请求进行访问控制设置
        http.authorizeHttpRequests((a) -> a
                //设置哪些路径可以直接访问，不需要认证
                .requestMatchers("/login.html", "/user/login").permitAll()
                .requestMatchers("/first/a", "/first/b").hasAnyAuthority("manager01", "manager02")
                .requestMatchers("/second/a", "/first/b").hasRole("role01")
                .requestMatchers("/second/b", "/second/c").hasRole("role02")
                .requestMatchers("/first/c").hasAuthority("manager01")
                //其他路径的请求都需要认证
                .anyRequest().authenticated()
        );

        // http.exceptionHandling().accessDeniedPage("/403.html");
        //关闭跨站点请求伪造csrf防护
        http.csrf(AbstractHttpConfigurer::disable);

        // 配置过滤器
        http.addFilterBefore(isLoginSecurityFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilter(new TokenSecurityFilter(authenticationManager(config)));
        // 配置没有登陆和未授权handler
        //http.exceptionHandling((e) ->
        //  e.authenticationEntryPoint(notLoginException)
        //         .accessDeniedHandler(notAccessException));
        return http.build();
    }

}
